// login and register
const express = require('express')
const User = require('../../models/schema/User')
const router = express.Router()
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const auth = require('../token')
const { SECRETKEY } = require('../../config/dbkeys')

/**
 * @url api/users/login
 * @method POST
 * @access public
 * @description login
 */
router.post('/login', async (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  const user = await User.findOne({
    username
  });
  if (!user) {
    return res.status(404).json({
      message: '用户不存在'
    })
  }
  // 比较密码
  const passwordValid = bcrypt.compareSync(
    password,
    user.password
  )
  if (!passwordValid) return res.status(404).json({
    message: '密码错误'
  })
  // jwt生成token,过期时间1小时
  const token = jwt.sign({
    id: String(user._id),
    username: user.username,
  } , SECRETKEY, { expiresIn: 60 * 60 * 1 })
  res.json({
    status: 200,
    message: '登录成功',
    token
  })
})

/**
 * @url api/users/register
 * @method POST
 * @access public
 * @description register
 */
router.post('/register', async (req, res) => {
  const user = await User.findOne({
    username: req.body.username
  });
  if (user) return res.status(404).json({
    message: '用户名已被占用'
  })
  const newUser = new User({
    username: req.body.username,
    password: req.body.password,
    area: req.body.area,
    age: req.body.age
  })
  newUser.save()
    .then(user => res.json({status: 200, message: '注册成功'}))
    .catch(err => {
      console.log(err)
    });
})

/**
 * @url api/users/checkusername
 * @method POST
 * @access public
 * @description check username
 */
router.post('/checkusername', async (req, res) => {
  const user = await User.findOne({
    username: req.body.username
  });
  if (user) return res.json({status: -1, message: '用户名已存在'})
  return res.json({status: 200, message: '该用户名可以使用'})
})

/**
 * @url api/users/profile
 * @method GET
 * @access private
 * @description get profile
 */
router.get('/findUser', auth, async (req, res) => {
  const user = await User.findById({ _id: req.body.id })
  if (user) {
    res.json(user);
  }
})

/**
 * @url api/users/getAllusers
 * @method GET
 * @access private
 * @description get all users
 */
router.get('/getAllusers', auth, async (req, res) => {
  const users = await User.find({})
  res.json({status: 200, users});
})

/**
 * @url api/users/updateUser
 * @method GET
 * @access private
 * @description update User info
 */
router.post('/updateUser', auth, async (req, res) => {
  const user = await User.findById({ _id: req.body.id })
  if (user) {
    user.age = req.body.age,
    user.area = req.body.area,
    user.save()
      .then(() => res.json({status: 200, message: '修改成功'}))
      .catch(ex => res.json({status: -1, message: '修改失败'}))
  } else {
    res.json({status: -1, message: '修改失败'})
  }
})

module.exports = router;